package com.zlj.jdbc.dbutils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.sql.DataSource;

import com.zlj.jdbc.jdbcUtils02.JdbcUtils;

/**
 * 这是DBUtils底层源码的山寨版(简便核心版)
 * @author bashen
 *
 * @param <T>
 */
public class QR<T> {
	private DataSource dataSource ;
	
	public QR(DataSource dataSource) {
		super();
		this.dataSource = dataSource;
	}

	public QR() {
		super();
	}

	/**
	 * 执行insert、update、delete操作
	 * @param sql
	 * @param params
	 * @throws SQLException 
	 */
    public int update(String sql, Object... params) throws SQLException {
    	Connection conn = null;
		PreparedStatement statement = null;
		try {
			conn = dataSource.getConnection();  //通过连接池得到连接对象
			System.out.println(conn);   
			statement = conn.prepareStatement(sql);  //得到statement
			initParams(statement,params);   //设置参数
			return statement.executeUpdate();    //执行
		} catch(SQLException e) {
			throw e;
		} finally {
			try {
				if(statement != null) {
					statement.close();
				}
				if(conn != null) {
					conn.close();
				}
			} catch(SQLException e1) {
				throw e1;
			}
		}
    }
    
    //给参数赋值
    private void initParams(PreparedStatement statement, Object... params) {
    	for(int i = 0; i < params.length; i++) {
    		try {
				statement.setObject(i + 1, params[i]);
			} catch (SQLException e) {
				e.printStackTrace();
			}
    	}
    }
    
    public T query(String sql, RsHandler<T> rs, Object... params) throws SQLException {
    	Connection conn = null;
		PreparedStatement statement = null;
		ResultSet resultSet = null;
		try {
			conn = JdbcUtils.getConnection();
			statement = conn.prepareStatement(sql);
			initParams(statement, params);
			resultSet = statement.executeQuery();
			return rs.handler(resultSet);
		} catch(SQLException e) {
			throw e;
		} finally {
			try {
				if(resultSet != null) {
					resultSet.close();
				}
				if(statement != null) {
					statement.close();
				}
				if(conn != null) {
					conn.close();
				}
			} catch(SQLException e1) {
				throw e1;
			}
		}
    }
}

//用来把结果集转换成需要的类型
interface RsHandler<T> {
	public T handler(ResultSet rs) throws SQLException;
}
